package jm.data.structure.set;

import java.util.LinkedList;

/**
 * @Description 链表实现set
 * @date 2022/4/23 14:34
 */
public class ListSet<E> implements Set<E>{

    private LinkedList<E> list = new LinkedList<>();

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public void clear() {
        list.clear();
    }

    @Override
    public boolean contains(E e) {
        return list.contains(e);
    }

    @Override
    public void add(E e) {
        int i = list.indexOf(e);
        if (i != -1){ // 如果已经存在就覆盖
            list.set(i,e);
        }else { // 不存在新添加
            list.add(e);
        }
    }

    @Override
    public void remove(E e) {
        int i = list.indexOf(e);
        if (i != -1){
            list.remove(e);
        }
    }

    @Override
    public void traversal(Visitor<E> visitor) {
        if (visitor == null){
            return;
        }
        int size = list.size();
        for (int i = 0; i < size; i++) {
            if (visitor.visit(list.get(i))) {
                return;
            }
        }
    }
}
